import configparser
import os

# if __name__ == '__main__':
#     from tech_components.imgworker.server import log
# else:
#     from . import log

__all__ = [
    "conf",
    "conf_file_dir_path"
]


class Section(configparser.SectionProxy):
    # a.b
    def __getattr__(self, k):
        # print(f"__getattr__({k})")
        return self[k]


def _swap_section(old: configparser.SectionProxy) -> Section:
    return Section(old.parser, old.name)


class Config(configparser.ConfigParser):
    # a.b
    def __getattr__(self, k):
        return self[k]

    def rebuild(self):
        # 进行转换
        for s in self.sections():
            old = self._proxies[s]
            self._proxies[s] = _swap_section(old)


conf_file_dir_path = os.path.curdir
conf = Config()


def _find_file(file_name: str = "config.ini", curr: str = os.path.curdir) -> str:
    curr = os.path.abspath(curr)
    fns = os.listdir(curr)
    for fn in fns:
        if fn == file_name:
            return f"{curr}/{fn}"
    parent = os.path.dirname(curr)
    if parent != "":
        return _find_file(file_name, parent)

    return ""


def __init(conf_file_path: str):
    _conf = Config()
    _conf.read(conf_file_path, encoding='UTF-8')

    # 默认值设置
    if _conf.has_section("app"):
        if not _conf.has_option("app", "data_dir_path"):
            _conf.set("app", "data_dir_path", "./data")

    global conf_file_dir_path
    conf_file_dir_path = os.path.dirname(conf_file_path)
    print(f"conf_file_dir_path={conf_file_dir_path}")

    for sec in _conf.sections():
        for k in _conf.options(sec):
            k = str(k)
            old_v = _conf.get(sec, k)
            v = old_v
            v = str(v).strip()
            if v == "\"\"":
                v = ""
            v = v.strip('"')
            # 特定的，对路径的替换。所有路径都是基于 config.ini 文件来定位的
            if k.endswith("_path"):
                if v.startswith("../"):
                    v = v.replace("..", os.path.dirname(conf_file_dir_path), 1)
                if v.startswith("./"):
                    v = v.replace(".", conf_file_dir_path, 1)
                v = os.path.abspath(v)
            if v != old_v:
                _conf.set(sec, k, v)

    _conf.rebuild()

    global conf
    conf = _conf


def _init():
    config_ini_file_path = _find_file()
    if config_ini_file_path == "":
        raise Exception(f"can not find config.ini file at all curr and parent dir")
    __init(config_ini_file_path)


_init()


def _test():
    print(conf)
    print(conf.get("app", "data_dir_path"))
    print(conf.get("app", "xxx", fallback="yyy"))
    print(conf.get("xxx", "xxx", fallback="yyy"))
    print(conf["app"].get("xxx", "yyy"))
    # print(conf["xxx"].get("xxx", "yyy"))
    print(conf.app["data_dir_path"])
    print(conf.app.data_dir_path)


if __name__ == '__main__':
    _test()
